﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;


namespace AnOtherBlog.Core.Providers.SQL
{
	/// <summary>
	/// Implementa el acceso a datos para la clase Page
	/// </summary>
	public partial class SQLDataProvider : DataProvider
	{

		#region Implement Abstract Class
		/// <summary>
		/// Obtiene una página
		/// </summary>
		/// <param name="id">Identificador de la página</param>
		/// <returns>Página</returns>
		public override Page PageSelect(Guid id)
		{
			Page page = null;
			using (SqlConnection connection = DataConnection)
			{
				connection.Open();
				using (SqlCommand command = new SqlCommand())
				{
					command.Connection = connection;

					command.CommandText = @"SELECT "
					+ @"PageID, Title, Description, PageContent, Keywords, DateCreated, DateModified, IsPublished, IsFrontPage, Parent, ShowInList, Slug, BlogID "
					+ @"FROM aob_Pages "
					+ @"WHERE PageID=@PageID";

					command.CommandType = CommandType.Text;
					command.Parameters.Clear();
					command.Parameters.Add(new SqlParameter("@PageID", id));

					using (SqlDataReader reader = command.ExecuteReader())
					{
						if (reader.Read())
						{
							page = SetPageProperties(reader, false);
						}
					}
				}
			}
			return page;
		}

		/// <summary>
		/// Inserta una página
		/// </summary>
		/// <param name="page">Página a insertar</param>
		public override void PageInsert(Page page)
		{

			using (SqlConnection connection = DataConnection)
			{
				connection.Open();
				using (SqlCommand command = new SqlCommand())
				{
					command.Connection = connection;

					// Nos aseguramos que no esté
					command.CommandText = @"DELETE FROM aob_Pages WHERE PageID=@PageID";
					command.CommandType = CommandType.Text;
					command.Parameters.Clear();
					command.Parameters.Add(new SqlParameter("@PageID", page.PageID));
					command.ExecuteNonQuery();

					command.CommandText = @"INSERT INTO aob_Pages "
					+ @"( PageID, Title, Description, PageContent, Keywords, DateCreated, DateModified, IsPublished, IsFrontPage, Parent, ShowInList, Slug, BlogID) VALUES "
					+ @"(@PageID,@Title,@Description,@PageContent,@Keywords,@DateCreated,@DateModified,@IsPublished,@IsFrontPage,@Parent,@ShowInList,@Slug,@BlogID)";

					command.CommandType = CommandType.Text;
					command.Parameters.Clear();
					command.Parameters.Add(new SqlParameter("@PageID", page.PageID));
					command.Parameters.Add(new SqlParameter("@Title", page.Title));
					command.Parameters.Add(new SqlParameter("@Description", page.Description));
					command.Parameters.Add(new SqlParameter("@PageContent", page.PageContent));
					command.Parameters.Add(new SqlParameter("@Keywords", page.Keywords));
					command.Parameters.Add(new SqlParameter("@DateCreated", page.DateCreated));
					command.Parameters.Add(new SqlParameter("@DateModified", page.DateModified));
					command.Parameters.Add(new SqlParameter("@IsPublished", page.IsPublished));
					command.Parameters.Add(new SqlParameter("@IsFrontPage", page.IsFrontPage));
					command.Parameters.Add(new SqlParameter("@Parent", page.Parent));
					command.Parameters.Add(new SqlParameter("@ShowInList", page.ShowInList));
					command.Parameters.Add(new SqlParameter("@Slug", page.Slug));
					command.Parameters.Add(new SqlParameter("@BlogID", Blog.Current.BlogID));
					
					command.ExecuteNonQuery();
				}
			}
		}

		/// <summary>
		/// Modifica una página
		/// </summary>
		/// <param name="page">Página a modificar</param>
		public override void PageUpdate(Page page)
		{
			PageInsert(page);
		}

		/// <summary>
		/// Suprime una página
		/// </summary>
		/// <param name="page">Página a suprimir</param>
		public override void PageDelete(Page page)
		{
			using (SqlConnection connection = DataConnection)
			{
				connection.Open();
				using (SqlCommand command = new SqlCommand())
				{
					command.Connection = connection;

					command.CommandText = @"DELETE FROM aob_Pages WHERE PageID=@PageID";
					command.CommandType = CommandType.Text;
					command.Parameters.Clear();
					command.Parameters.Add(new SqlParameter("@PageID", page.PageID));
					command.ExecuteNonQuery();
				}
			}
		}

		/// <summary>
		/// Obtiene la lista de todas las páginas
		/// </summary>
		/// <returns>Colección de páginas</returns>
		public override List<Page> PageList()
		{
			return PageList(false);
		}

		/// <summary>
		/// Obtiene la lista de todas las páginas
		/// </summary>
		/// <param name="isProxy">Modo de carga true=lectura reducida</param>
		/// <returns>Colección de páginas</returns>
		public override List<Page> PageList(bool isProxy)
		{
			List<Page> pages = new List<Page>();
			using (SqlConnection connection = DataConnection)
			{
				connection.Open();
				using (SqlCommand command = new SqlCommand())
				{
					command.Connection = connection;

					command.CommandText = @"SELECT "
					+ @"PageID, Title, Description, PageContent, Keywords, DateCreated, DateModified, IsPublished, IsFrontPage, Parent, ShowInList, Slug, BlogID "
					+ @"FROM aob_Pages "
					+ @"WHERE BlogID=@BlogID";

					command.CommandType = CommandType.Text;
					command.Parameters.Add(new SqlParameter("@BlogID", Blog.Current.BlogID));

					using (SqlDataReader reader = command.ExecuteReader())
					{
						while (reader.Read())
						{
							pages.Add(SetPageProperties(reader, isProxy));
						}
					}
				}
			}
			return pages;
		}

		#endregion

		#region Utilities Methods

		/// <summary>
		/// Fija todas las propiedades de una página
		/// </summary>
		/// <param name="reader">El <see cref="System.Data.SqlClient.SqlDataReader"/>que contiene los datos</param>
		/// <returns>Una nueva <see cref="AnOtherBlog.Core.Page"/> página</returns>
		private Page SetPageProperties(SqlDataReader reader)
		{
			return SetPageProperties(reader, false);
		}

		/// <summary>
		/// Fija todas las propiedades de una página
		/// </summary>
		/// <param name="reader">El <see cref="System.Data.SqlClient.SqlDataReader"/>que contiene los datos</param>
		/// <param name="isProxy">Lectura reducida</param>
		/// <returns>Una nueva <see cref="AnOtherBlog.Core.Page"/> página</returns>
		private Page SetPageProperties(SqlDataReader reader, bool isProxy)
		{
			Page page = new Page();

			if (!reader.IsDBNull(0)) page.PageID = reader.GetGuid(0);
			if (!reader.IsDBNull(1)) page.Title = reader.GetString(1);
			if (!reader.IsDBNull(2)) page.Description = reader.GetString(2);
			if (!isProxy)
			{
				if (!reader.IsDBNull(3)) page.PageContent = reader.GetString(3);
			}
			if (!reader.IsDBNull(4)) page.Keywords = reader.GetString(4);
			if (!reader.IsDBNull(5)) page.DateCreated = reader.GetDateTime(5);
			if (!reader.IsDBNull(6)) page.DateModified = reader.GetDateTime(6);
			if (!reader.IsDBNull(7)) page.IsPublished = reader.GetBoolean(7);
			if (!reader.IsDBNull(8)) page.IsFrontPage = reader.GetBoolean(8);
			if (!reader.IsDBNull(9)) page.Parent = reader.GetGuid(9);
			if (!reader.IsDBNull(10)) page.ShowInList = reader.GetBoolean(10);
			if (!reader.IsDBNull(11)) page.Slug = reader.GetString(11);
			if (!reader.IsDBNull(12)) page.BlogID = reader.GetInt32(12);

			return page;
		}

		// TODO: HAY QUE REVISAR ESTOS METODOS
		
		//public static Page PageImport(Guid id)
		//{
		//  // TODO: hay que mejorar este metodo 
		//  string data = File.ReadAllText(PageFile(id), System.Text.Encoding.Default);
		//  Page page = data.ConvertTo<Page>();
		//  return page;
		//}
		//public static void PageExport(Page page)
		//{
		//  // TODO: hay que mejorar este metodo
		//  File.WriteAllText(PageFile(page.Id), page.ToXml(), System.Text.Encoding.Default);
		//}
		//public static List<Page> PageImportList()
		//{
		//  List<Page> pages = new List<Page>();
		//  foreach (string file in Directory.GetFiles(PagePath(), "*.xml", SearchOption.TopDirectoryOnly))
		//  {
		//    FileInfo info = new FileInfo(file);
		//    string id = info.Name.Replace(".xml", string.Empty);
		//    Page page = PageImport(new Guid(id));
		//    pages.Add(page);
		//  }
		//  return pages;
		//}

		//private static string PageFile(Guid id)
		//{
		//  return PagePath() + id.ToString() + ".xml";
		//}
		//private static string PagePath()
		//{
		//  return System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Pages/");
		//}

		#endregion

	}
}
